import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  // 编辑路由规则
  {
    // login 路由规则
    path:'/',
    name:'login',
    component:()=>import('@/views/login/index.vue')
  },
  {
    path:"/login",
    redirect:'/'
  },
  {
    // 注册路由规则
    path:'/register',
    name:'register',
    component:()=>import('@/views/register/index.vue')
  },
  {
    // 首页的路由
    path:'/home',
    name:'home',
    component:()=>import('@/views/home/index.vue'),
    children:[
      {
        path:'main',
        component:()=>import('@/views/main/index.vue')
      },
      {
        path:'order',
        component:()=>import('@/views/order/index.vue')
      },
      {
        path:'help',
        component:()=>import('@/views/help/index.vue')
      },
      {
        path:'mine',
        component:()=>import('@/views/mine/index.vue')
      }
    ]
  },
  {
    path:'/detail/:id',
    component:()=>import('@/views/detail/index.vue')
  },
  {
    // 家政分类路由规则
    path:"/account/:id",
    component:()=>import('@/views/account/index.vue')
  },
  {
    // 添加常用地址路由
    path:'/address',
    component:()=>import('@/views/address/index.vue')
  }
]

// 重写push方法，解决路由跳转时出现的报错
// const originalPush = VueRouter.prototype.push
// VueRouter.prototype.push = function push(location) {
//   return originalPush.call(this, location).catch(err => err)
// }

const router = new VueRouter({
  routes
})

// 路由守卫 ，用于拦截路由
router.beforeEach((to,from,next)=>{
  if(to.path === '/login' || to.path === '/register' || to.path === '/'){
    next()
  }else{
    // 获取token
    const token = sessionStorage.getItem('token')
    if(token){
      next()
    }else{
      next('/login')
    }
  }
})

export default router
